﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Quartz;

namespace Agile.Redsys.Jobs
{
    public class ProcessRecurringTransactionsJob : IJob
    {


        public void Execute(IJobExecutionContext context)
        {
            try
            {
                ProcessRecurringTransactions(DateTime.Now);
            }
            catch (Exception ex)
            {
                ex = ex;
                Debug.Fail(ex.Message);
            }
        }

        private static IEnumerable<RedsysRecurringTransaction> _GetRecurringTransaction(Commerce commerce, DateTime now)
        {
            return commerce.RecurringTransactions.Where(rTx => rTx.Amount > 0 && rTx.Order != null && now >= rTx.StartDate &&
                                                               now < rTx.StartDate + TimeSpan.FromDays(rTx.Recurrences*rTx.Frequency) &&
                                                               !commerce.SuccessiveTransactions.Any(
                                                                                                    sTx =>
                                                                                                    sTx.Order == rTx.Order &&
                                                                                                    sTx.Date > now.AddDays(-rTx.Frequency) &&
                                                                                                    sTx.Date < now));
        }


        public static void ProcessRecurringTransactions(DateTime now)
        {
            foreach (Commerce commerce in CommerceManager.List)
            {
  
                foreach (RedsysRecurringTransaction rtx in _GetRecurringTransaction(commerce,now))
                {

                    try
                    {
                        if (RequestSucessiveTransaction(commerce, rtx))
                        {
                            RedsysSuccessiveTransaction stx = new RedsysSuccessiveTransaction {Date = now, Order = rtx.Order};
                            commerce.SuccessiveTransactions.Save(stx);
                        }
                    }
                    catch(Exception ex)
                    {
                        ex = ex;
                        Debug.WriteLine(ex.Message);
                    }
                   
                }
            }
        }

        private static bool RequestSucessiveTransaction(Commerce commerce, RedsysRecurringTransaction rtx)
        {
            int amount = (int)Math.Round(rtx.Amount * 100);
            string signature = SignatureHelper.GetSignature(amount,
                                                            rtx.Order,
                                                            commerce.MerchantCode,
                                                            978,
                                                            RedsysTransactionType
                                                                .SuccessiveTransaction,
                                                            string.Empty,
                                                            commerce.Secret);

            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(commerce.TestEnviroment
                                                                             ? "https://sis-t.redsys.es:25443/sis/realizarPago"
                                                                             : "https://sis.redsys.es/sis/realizarPago");

           
            string postData = "Ds_Merchant_Amount="+amount;
            postData += "&Ds_Merchant_TransactionType="+6;
            postData += "&Ds_Merchant_MerchantCode=" + commerce.MerchantCode;
            postData += "&Ds_Merchant_Terminal=" + commerce.Terminal;
            postData += "&Ds_Merchant_Order=" + rtx.Order;
            postData += "&Ds_Merchant_Currency=" + 978;
            postData += "&Ds_Merchant_MerchantSignature=" + signature;

            byte[] data = Encoding.GetEncoding("iso-8859-1").GetBytes(postData);
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
      

            using (Stream stream = request.GetRequestStream())
                stream.Write(data, 0, data.Length);

            using (HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse())
            using (StreamReader reader = new StreamReader(httpResponse.GetResponseStream()))
            {
                string response = reader.ReadToEnd();
                return response.Contains("RSisReciboOK");
            }
        }
    }
}
